package com.allen.filter;

import com.alibaba.fastjson.JSON;
import com.allen.common.BaseContext;
import com.allen.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author dragon1006xu@gmail.com
 * @create 2022/2/16 8:18
 */
@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        log.info("过滤器执行...");
        //0.强转两个对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取本次请求的URI
        String uri = request.getRequestURI();
        //2.判断本次请求是否需要过滤处理
        //新的方式实现:判断某些地址不需要进行过滤处理
        //1.定义不需要过滤处理的请求路径
        //2.使用路径匹配器 来去匹配请求地址是否属于不需要处理的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "user/loginout"};
        AntPathMatcher pathMatcher = new AntPathMatcher();
        boolean flag = false; //定义标识 表示当前请求地址是否需要过滤处理 如果不需要为true 需要为false
        for (String url : urls) {
            //url:不需要进行过滤处理的路径规则  uri:本次请求路径地址
            if (pathMatcher.match(url, uri)) {
                flag = true;
                break;
            }
        }
        if (flag) {
            //如果不需要过滤处理 直接放行
            filterChain.doFilter(request, response);
            return;
        }
        //如果需要处理 判断员工是否已经登录
        Object employee = request.getSession().getAttribute("employee");
        //登录了 就放行 正常访问
        if (employee != null) {
            //获取HttpSession中登录用户的信息，调用BaseContext方法将当前登录用户ID存入ThreadLocal
            BaseContext.setCurrentId((Long)employee);
            //登录了 就放行 正常访问
            filterChain.doFilter(request, response);
            return; //跳出方法 后面的代码不要执行
        }
        //判断用户是否登录  用户登录了就直接放行
        Object user = request.getSession().getAttribute("user");
        if (user != null) {
            BaseContext.setCurrentId((Long)user);
            filterChain.doFilter(request, response);
            return;
        }
        //没有登录 就返回未登录 跳转登录页面
        response.getWriter().print(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
